import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/widgets/select_wifi.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttlock.dart";
import "package:ttlock_flutter/ttgateway.dart";


enum ConfigType {
  sett,
  unset,
}

class LockWifi extends StatefulWidget {
  final String lockData;
  final int lockId;
  final ConfigType type;
  final String? wifi;
  const LockWifi({super.key, required this.lockData, required this.lockId, required this.type, this.wifi});

  @override
  State<StatefulWidget> createState() => _LockWifiState();
}

class _LockWifiState extends State<LockWifi> {
  final _formKey = GlobalKey<FormState>();
  String? wifi;
  String? wifiPassword;
  List wifiList = [];
  bool isScanning = false;


  void _getWifiList() async {
    final result = await Stacker.pushNamed(
      Keys.DEVICE_SELECT_WIFI, 
      arguments: {
        'type': ConfigWifiType.lock,
        'deviceData': widget.lockData,
      }
    );
    
    if (result != null && result is Map) {
      setState(() {
        wifi = result["wifi"];
      });
    }
  }

  void _submitForm() {
    if (_formKey.currentState!.validate())  {
      // 处理表单提交逻辑
      EasyLoading.show();
      // 这里可以添加连接Wifi的逻辑
      TTLock.configWifi(wifi!, wifiPassword!, widget.lockData, () {
        if (widget.type == ConfigType.unset) {
          /// 配置服务器地址
          TTLock.configServer("wifilock.ttlock.com", "4999", widget.lockData, () async {
            /// 关闭门锁省电模式
            TTLock.setLockConfig(TTLockConfig.wifiLockPowerSavingMode, false, widget.lockData, () async {
              await lockApi.lockSetting(widget.lockId, {
                "lockId": widget.lockId,
                "changeType": 1,
                "type": 10,
                "value": 2,
              });
            }, (errorCode, errorMsg) {
              EasyLoading.showError("$errorCode: $errorMsg");
            },);
            /// 配置成功后调用后台更新wifi接口，即可使用远程开锁
            Map<String, dynamic> data = {
              "lockId": widget.lockId,
              "wifiName": wifi,
              "wifiPassword": wifiPassword
            };
            await lockApi.updateNetwork(data);
            EasyLoading.showSuccess("wifi配置成功");
            Stacker.pushNamedAndRemoveUntil(Keys.DEVICE_LOCK, ModalRoute.withName(Keys.MAIN));
          }, (errorCode, errorMsg) {
            print("$errorCode: $errorMsg");
            EasyLoading.showError("服务器配置失败");
          });
        } else {
          EasyLoading.showSuccess("wifi配置成功");
          Stacker.pushNamedAndRemoveUntil(Keys.DEVICE_LOCK, ModalRoute.withName(Keys.MAIN));
        }
      }, (errorCode, errorMsg) {
        print("$errorCode: $errorMsg");
        EasyLoading.showError("wifi配置失败");
      });
    }
  }

  @override
  void initState() {
    super.initState();
    if (widget.wifi != null) {
      setState(() {
        wifi = widget.wifi;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "配置wifi",
      child: Container(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              MenuBlock(
                items: [
                  MenuBlockItem(
                    text: "选择Wifi",
                    suffix: Text(wifi ?? "请选择"),
                    onTap: _getWifiList,
                  ),
                  MenuBlockItem(
                    text: "Wifi密码",
                    showArrow: false,
                    suffix: SizedBox(
                      width: 200,
                      child: TextFormField(
                        obscureText: true,
                        textAlign: TextAlign.right,
                        decoration: const InputDecoration(
                          hintText: "请输入Wifi密码",
                          border: InputBorder.none,
                        ),
                        validator: (value) {
                          if (wifi != null && (value == null || value.isEmpty)) {
                            return "请输入Wifi密码";
                          }
                          return null;
                        },
                        onChanged: (value) {
                          wifiPassword = value;
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 48),
              Row(
                children: [
                  Expanded(child: Button(
                    onPressed: _submitForm,
                    child: const Text("确认"),
                  ),),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

}